package dbinit;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import core.address.model.AddressType;
import core.util.HibernateCoreUtil;

public class InitAddressType {
	public static AddressType getAddressTypeByUuid(Long uuid)
	{
		AddressType at = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				at = (AddressType) session.get(AddressType.class, uuid);
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return at ;
	}
	public static AddressType getAddressTypeByName(String addresstype)
	{
		AddressType at = null ;
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		try
		{
			transaction = session.beginTransaction();
			at = (AddressType)session.createCriteria(AddressType.class).add(Restrictions.eq("addressType" ,addresstype )).uniqueResult();
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally
		{
			session.close();
		}
		return at;
	}
	public static Long doinit(String addressType)
	{
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		AddressType at = getAddressTypeByName(addressType);
		if(at == null)
		{
			at =  new AddressType();
		}
		
		at.setAddressType(addressType);
		Long uuid = null;
		try
		{
			transaction = session.beginTransaction();
		    at = (AddressType)session.merge(at);
		    uuid = at.getUuid();
			transaction.commit();
		}
		catch(HibernateException he)
		{
			he.printStackTrace();
		}
		finally
		{
			session.close();
		}
		return uuid ;
	}

}
